package cn.tedu.reflection;

import org.testng.annotations.Test;

import java.lang.reflect.Constructor;
import java.util.Arrays;


public class TestReflection {
    /*单元测试方法：是java测试的最小单位，使用灵活
     * 语法要求：         @Test +void+没有参数+public
     * 注意使用时需要导包：Add Junit4 to classpath
     * import org.junit.Test*/
    @Test
    public void test() throws Exception {
        /*本方法的参数是目标类的全路径（包名+类名）*/
        Class<?> student1 = Class.forName("cn.tedu.reflection.Student");
        Class<Student> student2 = Student.class;
        /*本方法创建的一个匿名对象，匿名对象没有名字*/
        Class<? extends String> student3 = new String().getClass();
        System.out.println(student1);//class cn.tedu.reflection.Student
        System.out.println(student1.getName());//cn.tedu.reflection.Student
        System.out.println(student1.getPackage());//package cn.tedu.reflection
        System.out.println(student1.getSimpleName());//Student
        System.out.println(student1.getCanonicalName());//cn.tedu.reflection.Student
        System.out.println(student1.getTypeName());//cn.tedu.reflection.Student
    }

    //3.通过单元测试获取构造方法
    @Test
    public void test1() {
        Class<Student> studentClass = Student.class;
        Constructor<?>[] constructors = studentClass.getConstructors();
        for (Constructor c : constructors) {
            //System.out.println(c.getName());//获取构造器名字
            Class[] parameterTypes = c.getParameterTypes();//获取构造器类型
            System.out.println(Arrays.toString(parameterTypes));
        }
    }

    @Test
    public void test2() throws ClassNotFoundException {
        Class<?> name = Class.forName("cn.tedu.reflection.Student");
        Constructor<?>[] constructors = name.getConstructors();
        for (Constructor c :
                constructors) {
            System.out.println(c.getName());
            System.out.println(Arrays.toString(c.getParameterTypes()));
        }
    }
}
